import requests
import os
import argparse
import json
import cams
import time
import cv2
import numpy as np
import svar

osdk=svar.load('svar_osdk')

env=osdk.LinuxSetup(True)
vehicle = env.getVehicle()
rtmv=None
height=0

def callback_buf(buf):
  global rtmv
  global_pos=vehicle.broadcast.getGlobalPosition()
  height=global_pos["height"]
  if height < 50:
    return
  if rtmv is None:
    rtmv = open(str(time.time())+".rtmv",'wb',buffering=0)
  mem=memoryview(buf)
  rtmv.write(mem.tobytes())

# start rtmv publish
options={}
options["camera_position"]=osdk.OSDK_CAMERA_POSITION_NO_1
options["playload_index"]=osdk.PAYLOAD_INDEX_0
options["h264_source"]=osdk.OSDK_CAMERA_SOURCE_H20T_ZOOM
options["enable_rtmv"]=True
node=osdk.VehicleNode(vehicle,options)
sub_rtmv=osdk.messenger.subscribe("rtmv",0,callback_buf)

def stitch_process():
  # prepare task
  parameters={}
  parameters["map2dfusion.auto_zoom"]=2
  parameters["pointsfusion.use_terrainfusion"]=True
  parameters["terrainfusion.auto_zoom"]=0
  parameters["terrainfusion.max_zoom"]=30
  parameters["pointsfusion.clone_frame"]=0
  parameters["pointsfusion.dense_method"]=2
  parameters["pointsfusion.fulldp"]=0
  
  cameras = cams.cameras
  server='http://192.168.1.232:1024'
  task={"task":"online_points","parameters":parameters,"dataset":{"type":"images_stream","cameras":cameras,"images":[]}}
  headers = {'Content-Type': 'application/json;charset=UTF-8'}
  r = requests.request("post",server+"/task",json=task,headers=headers)
  print("task created with response",r.text)
  taskid=r.json().get('taskid')
  
  def post_image(taskid,imgfile):
    taskjson=json.dumps({"image":imgfile})
    jsonfile = os.path.splitext(os.path.split(imgfile)[1])[0]+'.json'
    files={
        "f.json" : (jsonfile,taskjson.encode()),"f.jpg" : open(imgfile, "rb")
       }
    r = requests.post(server+"/task/"+ taskid+"/frame", None, files=files)
    print(r.text)
  
  # start images fetching
  downloaded={}
  savefolder='.'
  is_first=False
  
  while(False):
    vehicle.cameraManager.setModeSync(osdk.PAYLOAD_INDEX_0,osdk.MEDIA_DOWNLOAD,2)
    vehicle.cameraManager.obtainDownloadRightSync(osdk.PAYLOAD_INDEX_0,True,2)
  
    file_list=vehicle.cameraManager.reqFileList(osdk.PAYLOAD_INDEX_0)
  
    media=file_list.media
    print("there are ",len(media),"files")
  
    for m in media:
      if m.fileName.find('WIDE') < 0:
        continue
      if m.fileName.find('198000000') > 0:
        print("abort",m)
        continue
      file_path=os.path.join(savefolder,m.fileName)
  
      if downloaded.get(m.fileIndex) != None:
        print("abort",m.fileName)
        continue
  
      if os.path.exists(file_path):
        continue
      if is_first:
        downloaded[m.fileIndex]=m
        continue
      print("reqesting file",file_path,"id",m.fileIndex)
      ret=vehicle.cameraManager.reqFileData(osdk.PAYLOAD_INDEX_0,m.fileIndex,file_path)
      print("reqest finished with code:",ret)
      if ret !=0:
        osdk.ErrorCode.printErrorCodeMsg(ret)
        break
      if taskid:
        post_image(taskid,file_path)
    
    if len(media) > 0:
      is_first=False
  
    time.sleep(3)
  
  if taskid:
    r = requests.request("post",server+"/task/"+ taskid+"/frame",json={},headers=headers)
    print(r.text)

from flask import Flask
app = Flask(__name__)

@app.route("/global_position")
def hello():
    return vehicle.broadcast.getGlobalPosition()

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=1234)
